package com.ody.util.code;

import com.google.common.base.Splitter;
import com.odianyun.util.io.FileUtils;
import com.odianyun.util.io.ZIPUtils;
import org.springframework.util.StringUtils;

import javax.swing.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class Updater {
	
	public static boolean update(String currentPath, String checkUrl, String currentVersion, boolean debug) throws Exception {
		String _checkUrl = checkUrl;
		if(_checkUrl == null || _checkUrl.trim().length() == 0) {
			_checkUrl = Const.DEFAULT_CHECK_URL;
		}
		HttpURLConnection conn = (HttpURLConnection) new URL(_checkUrl).openConnection();
		BufferedReader br = null;
		try {
			int resCode = conn.getResponseCode();
			if(resCode != 200) {
				conn.disconnect();
				return false;
			}
			
			br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String version = br.readLine();
			long cv = VersionUtils.convert2Long(currentVersion, 3);
			long v = VersionUtils.convert2Long(version, 3);
			if(v > cv) {
				String updateUrl = br.readLine();
				br.close();
				conn.disconnect();
				conn = (HttpURLConnection) new URL(updateUrl).openConnection();
				resCode = conn.getResponseCode();
				if(resCode != 200) {
					conn.disconnect();
					return false;
				}
				
				Map<String, String> paramMap = Collections.emptyMap();
				String params = br.readLine();
				if (StringUtils.hasText(params)) {
					for (String item : Splitter.on("&").trimResults().split(params)) {
						List<String> kv = Splitter.on("=").trimResults().splitToList(item);
						if (kv.size() > 0) {
							paramMap.put(kv.get(0), kv.size() > 1 ? kv.get(1) : null);	
						}
					}
				}
				
				File file = new File(currentPath);
				if(Const.CODE_GENERATOR_NAME.equals(file.getName())) {
					ZIPUtils.unzip(conn.getInputStream(), file.getParentFile());
					if (paramMap.containsKey("deleteMeConfigFile")) {
						deleteMeConfigFile(file);
					}
					return true;
				}
				
				return false;
			}
		} catch (Exception e) {
			if (debug) {
				throw e;
			}
		} finally {
			conn.disconnect();
			if(br != null) br.close();
		}
		
		return false;
	}
	
	private static void deleteMeConfigFile(File dir) throws Exception {
		for (String filename : dir.list((d, n) -> {
			return Const.ME_CONFIG_FILE_REGEX.matcher(n).find();
		})) {
			FileUtils.delete(new File(dir, filename));
		}
	}
	
	public static void main(String[] args) throws Exception {
		try {
            String checkUrl = Const.DEFAULT_CHECK_URL;
		    if (args.length > 0) {
                for (String arg : args) {
                    if (arg.startsWith("--updateUrl=")) {
                        checkUrl = arg.substring("--updateUrl=".length());
                    }
                }
            }
            boolean isUpdate = Updater.update(Main.class.getClassLoader().getResource("").getPath(), checkUrl, Const.VERSION, true);
            if (isUpdate) {
                JOptionPane.showMessageDialog(null, "更新成功");
            } else {
                JOptionPane.showMessageDialog(null, "当前已是最新版本");
            }
        } catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
			e.printStackTrace();
		}
	}

}
